import React, { useRef, useState } from 'react'
import { Input, Image, Button, message } from 'antd';

import { addBanner } from '../../api/banner';
import { useNavigate } from 'react-router'


export default function Index() {

    const router = useNavigate()

    const [imgUrl, setImgUrl] = useState('')

    // 创建一个 url 
    // const inpRef = useRef()
    const inpRef = React.createRef()

    const changeImage = (e) => {
        // console.log(e.target.files);

        // URL.createObjectURL()

        const reader = new FileReader()
        reader.readAsDataURL(e.target.files[0])
        reader.onload = () => {
            // console.log(reader.result);
            setImgUrl(reader.result)
        }
    }


    const [alt, setAlt] = useState('')
    const [link, setLink] = useState('')

    // 添加按钮的点击事件
    const addClick = () => {

        // console.log(alt, link, imgUrl);
        addBanner({
            alt,
            link,
            img: imgUrl
        }).then(res => {
            // console.log(res);
            if (res.code == 200) {
                message.success(res.message)

                setAlt('')
                setLink('')
                setImgUrl('')

                // 跳转页面
                router('/banner/list')
            }
        })
    }
    return (
        <div>
            <h2> 添加轮播图 </h2>

            <Input value={link} onChange={e => setLink(e.target.value)} placeholder="请输入 link" />
            <Input value={alt} onChange={e => setAlt(e.target.value)} placeholder="请输入 alt" />
            <br /><br /><br />

            <input hidden ref={inpRef} onChange={changeImage} type="file" />

            <Button onClick={() => { inpRef.current.click() }}>选择图片</Button>

            <br /><br /><br />
            <Image style={{ width: 100 }} src={imgUrl} />
            <br /><br /><br />

            <Button onClick={addClick}>添加</Button>

        </div>
    )
}
